<?php
/**
 * Created by 流年酷.
 * User: WenZhen Miao
 * Date: 2018-04-11
 * Time: 下午 4:15
 */

namespace app\admin\model;

use think\Model;

class User extends Model
{
	// 当前模型对应的数据表名称
	protected $table = 'lnk_admin';

	protected $pk = 'id';
	protected $request;
	protected $log;

	protected function initialize(){
	    $this->log=model('Log');
    }
	/**
	 * [login 登录]
	 * @Author WenZhen Miao
	 * @DateTime  2018-04-12T10:45:33+0800
	 * @param     [string]                   $username [账号]
	 * @param     [string]                   $password      [密码]
	 * @param     [string]                   $verify [验证码]
	 * @return    [type]                               [description]
	 */
	public function login($username,$password,$verify){

		if( !captcha_check($verify))
		{
			$this->error = '验证码错误';
	        return false;
		}
		$data = User::where('username', $username)->find();
		if(!$data){
			$this->error = '该账号不存在';
			return false;
		}
		if($data['password']!==lnk_pass($password,$data['encrypt'])){
			$this->error = '密码错误';
			return false;
		}
		if($data['status']!=='正常'){
			$this->error = '该账号已被禁用';
			return false;
		}
		//登录
		$this->autoLogin($data['id']);
		//获得菜单
		return $data;
	}
	/**
	 * 自动登录用户
	 * @param  integer $user 用户id
	 */
	private function autoLogin($id){
		/* 更新登录信息 */
		$user = User::get($id);
		$user->login_num+=1;
		$user->last_time=time();
		$user->create_time=time();
		$user->last_ip=ip2long(request()->ip());
		$user->login_token=lnk_pass($user->last_ip);
		$user->save();

		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'uid'             => $id,
			'username'        => $user->username,
			'last_login_time' => $user->last_time,
			'login_token'     => $user->login_token,
		);
		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth));
		$this->log->add_log($_SERVER['PHP_SELF'],'管理员['.$auth['username'].']登录:<font style="color:red">成功</font>');

	}
	//状态值转换
	public function getStatusAttr($value)
	{
		$status = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核'];
		return $status[$value];

	}
}